// sessionStorage.setItem("bpuk", "0447c2bc7732ebcc93fa673c51ed1df467d0bb253c46b3c2bc748691a767babff45f39819b0c4d25a1927d8f420efcb24b66129180070ef7d7eaf83a95e797c289")
// sessionStorage.setItem("userId", "testuserid1")
// sessionStorage.setItem("unitId", "111")
// sessionStorage.setItem("iscp_port", "14800")
// // sessionStorage.setItem("localUrlLink", "http://27.196.143.71:")
// sessionStorage.setItem("newMenus", JSON.stringify([{
//     'id': 1,
//     'buttonIds': ['1-report', '1-news']
//   },{
//     'id': 12,
//     'buttonIds': ['12-trip']
//   }]))
// // localUrlLink = "http://172.20.10.5:"

// if (sessionStorage.getItem("iscp_port")) {
//   iscp_port = sessionStorage.getItem("iscp_port");
// } else {
//   iscp_port = "";
// }

// if (sessionStorage.getItem("localUrlLink")) {
//   localUrlLink = sessionStorage.getItem("localUrlLink");
// } else {
// }


// function closeApp() {

// }

function checkFileNameForSensitiveWords(fileName) {
  const sensitiveWords = ["法轮功","中共中央办公厅发电","中共中央办公厅发电","中办信息综合室","中办发电","中办秘书局","中办通报","中央委员会","中央办公厅","中标价格","同业对标","同修","标底","二次系统安全防护","电价调整","稽核报告","预算报告","普通事项","内部事项","内部资料","重要事项","决算报告","秘密","机密","绝密","商密","普通商密","商业秘密","核心商密","安全保卫","法律纠纷",'邪党',"中长期发展规划","财务预算报告","电价调整方案","城市电网管线","年度综合计划","公司驻外津补贴标准","年度工资总额预算","工资总额计划","清算报告","经济活动分析报告","年度投资计划报告","投资完成情况报告","安全生产事故调查报告","招标方案","签报","薪酬方案","职工代表提案","电网地理接线图","电网年度运行方式报告"];
  for (let i = 0; i < sensitiveWords.length; i++) {
    if (fileName.includes(sensitiveWords[i])) {
      return true;
    }
  }
  return false;
}

// let vconsole = new VConsole()
// vconsole.showSwitch()
// 隐藏 vConsole 的开关按钮
// $(() => {
//     let vconsoleFlag = sessionStorage.getItem("vconsoleFlag")
//     if (vconsoleFlag != "true") {
//         vconsole.hideSwitch()
//     }
// })

/**
 * 
 * @param {全部字符} str 
 * @param {匹配字符} char 
 * @returns 字符匹配位置
 */
function findAllIndexes(str, char) {
  let indexes = [];
  let pos = str.indexOf(char); // 查找第一个匹配的位置

  while (pos !== -1) {
      indexes.push(pos); // 将位置添加到数组中
      pos = str.indexOf(char, pos + 1); // 从下一个位置继续查找
  }

  return indexes;
}

// 格式化日期 format('yyyy-MM-dd hh:mm:ss:SS 星期w 第q季度')
function dateFormat(format, date) {
  if (!date) {
    date = new Date();
  } else if (typeof (date) == 'string') {
    date = new Date(date);
  }
  var Week = ['日', '一', '二', '三', '四', '五', '六'];
  var o = {
    'y+': date.getYear(), //year
    'M+': date.getMonth() + 1, //month
    'd+': date.getDate(), //day
    'h+': date.getHours(), //hour
    'H+': date.getHours(), //hour
    'm+': date.getMinutes(), //minute
    's+': date.getSeconds(), //second
    'q+': Math.floor((date.getMonth() + 3) / 3), //quarter
    'S': date.getMilliseconds(), //millisecond
    'w': Week[date.getDay()]
  }
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
    }
  }
  return format;
}

/**
 * 获取html字符串中的第一个标签
 * @param {html字符串} str 
 * @returns 
 */
function getFirstHtmlTag(str) {
  const regex = /<([a-z][a-z0-9]*)\b[^>]*>/i;
  const match = regex.exec(str);
  return match ? match[0] : null;
}

/**
 * 替换字符串,往前后5个字符去找，未找到递归+5，直到找到或递归完成所有的字符
 * @param {原文} str
 * @param {替换字符串} newChar
 * @param {替换开始位置} start
 * @param {替换结束位置} end
 * @param {被替换的文字} cont
 * @param {往前后查找的偏差数,默认5} offset
 * @returns
 */
function replaceCharAt(str, newChar, start, end, cont, offset) {
  var newStr = "";
  offset = offset || 5
  let _start = (start - offset) > 0 ? (start - offset) : 0
  if(_start > str.length) {
    _start = str.length - offset
  }
  let _end = end + offset > str.length ? str.length : end + offset
  if (_end >= str.length) {
    _end = str.length
  }
  let tstr = str.substring(_start, _end)
  if((0 < _start || _end < str.length) && (tstr.indexOf(cont) < _start || tstr.indexOf(cont) > _end)) {
    return replaceCharAt(str, newChar, _start, _end, cont)
  }
  tstr = tstr.replace(cont, newChar)
  newStr = str.substring(0, _start) + tstr;
  if (_end > str.length) {
    return newStr;
  }
  newStr += str.substring(_end);
  return newStr;
}

/**
 * 流式请求,需要导入stream.js,streamMsg.js两个文件
 * @param {请求地址} url 
 * @param {请求参数JSON} param 
 * @param {成功回调} success 
 * @param {失败回调} error 
 */
function streamChat(url, param, success, error, close, open) {

  if (typeof EventSource !== "undefined") {
    console.log("SSE supported in this browser.");
  } else {
    console.log("SSE not supported in this browser.");
  }
  if (sessionStorage.getItem("iscp_port")) {
    iscp_port = sessionStorage.getItem("iscp_port");
  } else {
    iscp_port = "";
  }
  let AuthenticationSession = sessionStorage.getItem("Authentication");
  param.timestamp = new Date().getTime() + ""
  let data = JSON.stringify(param);
  console.log("会话参数是:", JSON.stringify(param));
  let sign = sm3(data);

  let abortCtrl = new AbortController(); // 创建AbortController实例，以便中止请求
  fetchEventSource(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authentication: AuthenticationSession,
      sign: sign
    },
    body: data,
    openWhenHidden: true, // 取消visibilityChange事件
    signal: abortCtrl.signal, // AbortSignal
    onopen: async (response) => {
      console.log("成功连接到服务器", response)
      if(open) {
        open(response)
      }
    },
    onmessage: (event) => {
      if(success) {
        // console.log("eventstream流式返回结果", event.data)
        success(JSON.parse(event.data));
      }
    },
    onclose: (ee) => {
      console.log("对话结束", ee);
      if(close) {
        close(ee);
      }
    },
    onerror: (err) => {
      console.log("对话异常", err);
      if(error) {
        error(err);
      }
      abortCtrl.abort();
      // 直接抛出错误，避免反复调用
      throw err;
    },
  });
  return abortCtrl
}

/**
 * 判断是否iphone
 */
function compatibleInput() {
  //获取浏览器的userAgent,并转化为小写
  var ua = navigator.userAgent.toLowerCase();
  //判断是否是苹果手机，是则是true
  var isIos = ua.indexOf("iphone") != -1 || ua.indexOf("ipad") != -1;
  return isIos
}

/**
 * html转为MD，需要导入turndown.js
 * @param {待转换的html} html 
 * @returns 
 */
function html2Md(html) {
  var turndownService = new TurndownService()
  return turndownService.turndown(html)
}

/**
 * 计算文件大小
 * @param {文件大小} fileSize 
 * @returns 
 */
function calcFileSize(fileSize) {
  let kbf = (Math.floor((fileSize / 1024) * 100) / 100).toFixed(2);
  if (kbf > 1000) {
      //显示 MB
      return (Math.floor((fileSize / (1024 * 1024)) * 100) / 100).toFixed(2) + 'MB';
  }
  return kbf + 'KB';
}

/*-----------上传文件-----------*/
/**
 * 
 * @param {外部调用的对象this} obj 
 * @param {文件校验回调} fileValid 
 * @param {上传完成回调} complete 
 */
function uploadFunc(obj, fileValid, complete) {
  let _that = obj
  wx.invoke("ext_FileBrowser_StartPreView", {}, function (res) {
      _that.channelId = "temp_upload_" + createNonceStr(8) + new Date().getTime() + "";

      if (compatibleInput()) {
          const suffix = res.name.split('.').reverse()[0]

          if(!fileValid(suffix.toLocaleLowerCase())){
            //文件校验
            return
          }
          checkList(complete, _that, res.filePath, res.name, res.size)
      } else {
          let recordArr = JSON.parse(res.result)
          const suffix = recordArr[0].name.split('.').reverse()[0]
          if(!fileValid(suffix.toLocaleLowerCase())){
            //文件校验
            return
          }
          checkList(complete, _that, recordArr[0].path, recordArr[0].name, recordArr[0].fileSize)
      }
  })
}
/**
 * 上传文件请求
 * @param {完成回调} complete 
 * @param {外部调用的this} obj 
 * @param {文件路径} path 
 * @param {文件名} name 
 * @param {文件大小} fileSize 
 * @param {文件hash} hash 
 * @param {文件分块索引} index 
 */
function checkList(complete, obj, path, name, fileSize, hash, index) {
  if($(".curtain")) {
    $(".curtain").css("display", "block");
  }
  let that = obj
  let iscp_port
  if (sessionStorage.getItem("iscp_port")) {
      iscp_port = sessionStorage.getItem("iscp_port");
  } else {
      iscp_port = ""
  }
  let Authentication = sessionStorage.getItem("Authentication");
  const timestamp = new Date().getTime() + ""
  let userId = sessionStorage.getItem("userId");
  let sign = sm3(timestamp + "&" + userId)
  wx.invoke("ext_Net_FragmentUpload", {
      data: {
          serverAddress: localUrlLink + iscp_port + `/tjAiAssistant/storage/splitUpload2?channelId=${that.channelId}`,
          filePath: path,
          fragmentSize: that.CHUNK_SIZE,
          fileName: name,
          fileHash: hash ? hash : '',
          upLoadFragmentIndex: index ? index : '',
          channelId: that.channelId,
          headerData: {
              sign: sign,
              userId: userId,
              type: '',
              timestamp: timestamp,
              Authentication: Authentication,
          }
      },
  }, function (res) {
      if (res.err_msg.endsWith(":ok")) { //成功结果
          //上传完成
          complete(that.channelId, name, fileSize, res)
          if($(".curtain")) {
            $(".curtain").css("display", "none");
          }
      } else if (res.err_msg.endsWith(":cancel")) {
          return
      } else {
          //上传失败
          if (that.myindex != Number(res.upLoadFragmentIndex)) {
              that.myindex = Number(res.upLoadFragmentIndex);
              that.retryNum = 0;
          }
          setTimeout(() => {
              if (that.retryNum > 4) {
                  var btnArray = ["取消", "确定"];
                  var i = 0
                  mui.confirm(
                      "是否进行重试？",
                      "上传失败",
                      btnArray,
                      (e) => {
                          if (i > 0) return
                          i++
                          if (e.index == 1) {
                              that.checkList(complete, obj, path, name, fileSize, res.fileHash, res.upLoadFragmentIndex)
                          } else {
                          }
                      }
                  );
              } else {
                  that.retryNum++

                  that.checkList(complete, obj, path, name, fileSize, res.fileHash, res.upLoadFragmentIndex)
              }

          }, (that.retryNum + 1) * 1000)

      }
  })
}

/**
 * 计算文件大小，显示为   xxxKB | xxxMB
 * @param {文件大小} fileSize 
 * @returns 
 */
function calcFileSize(fileSize) {
  let kbf = (Math.floor((fileSize / 1024) * 100) / 100).toFixed(2);
  if (kbf > 1000) {
      //显示 MB
      return (Math.floor((fileSize / (1024 * 1024)) * 100) / 100).toFixed(2) + 'MB';
  }
  return kbf + 'KB';
}
/*-----------上传文件-----------*/
/**
 * 创建指定长度的id
 * @param {长度} len 
 * @returns 
 */
function createNonceStr(len) {
  var e = len ? len : 16;
  var t =
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
      a = t.length,
      n = "";
  for (i = 0; i < e; i++)
      n += t.charAt(Math.floor(Math.random() * a));
  return n;
}

/**
 * 生成uuid
 * @returns 
 */
function generateUUID() {
  var d = new Date().getTime();
  var d2 = (performance && performance.now && (performance.now() * 1000)) || 0; //Time in microseconds since page-load or 0 if unsupported
  return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      var r = Math.random() * 16;
      if (d > 0) {
          r = (d + r) % 16 | 0;
          d = Math.floor(d / 16);
      } else {
          r = (d2 + r) % 16 | 0;
          d2 = Math.floor(d2 / 16);
      }
      return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
}

/**
 * 文件预览,id与channelId 二选一
 * @param {文件信息对象} file:
 *  id: id, 
 *  channelId: channelId,
 *  name: name,
 *  size: size
 */
function myPreviewFile(file) {
  console.log('预览文件', file)
  const userId = sessionStorage.getItem("userId");
  let id = file.viewId || file.id
  let downUrl = localUrlLink + iscp_port + '/tjAiAssistant/common/download';
  downUrl += '?id=' + id + '&userId=' + userId;
  let Authentication = sessionStorage.getItem("Authentication");
  let timestamp = new Date().getTime()+"";
  let sign = sm3(timestamp + '&' + id)
  downUrl += '&Authentication=' + Authentication + '&timestamp=' + timestamp + '&sign=' + sign;
  console.log('预览地址', downUrl)
  wx.invoke('previewFile', {
      url: downUrl,
      isLocalUrl: 0,
      name: file.name || file.fileName,
      size: file.size || file.fileSize,
      hidePreviewMenuList : []
  });
}

function syncToast(msg, duration, type, root) {
  var activeClass = "my-toast-active";
  var f = document.createElement("div");
  var imgSrc = root ? "./yr/images/"+type+".png" : "../../yr/images/"+type+".png"
  return f.classList.add("my-toast-container"), f.innerHTML = '<div class="my-toast-message"><img src="'+imgSrc+'">' + msg + "</div>", f.addEventListener("webkitTransitionEnd", function () {
      f.classList.contains(activeClass) || (f.parentNode.removeChild(f), f = null)
  }), f.addEventListener("click", function () {
      f.parentNode.removeChild(f), f = null
  }), document.body.appendChild(f), f.offsetHeight, f.classList.add(activeClass), setTimeout(function () {
      // f && f.classList.remove(activeClass)
      f.parentNode.removeChild(f), f = null
  }, duration), {
      isVisible: function () {
          return !!f
      }
  }
}
function mySyncToInner(messageTitle, message, operatorType, operatorBasic) {
  mui.confirm("是否同步至内网网站？", "消息提醒", ["取消", "确定"], (e) => {
      if (e.index == 1) {
          syncToInnerReq(messageTitle, message, operatorType, operatorBasic)
      } else {
      }
  });
}
/**
 * 
 * @param {邮件标题} messageTitle 
 * @param {邮件内容} message 
 * @param {操作分类} operatorType 后台ToEmailEnum枚举类，前面两位10
 * @param {具体操作} operatorBasic 后台ToEmailEnum枚举类，第三位开始
 */
function syncToInnerReq(messageTitle, message, operatorType, operatorBasic) {
  if($(".curtain")) {
    $(".curtain").css("display", "block");
  }
  const userId = sessionStorage.getItem("userId");
  const orgId = sessionStorage.getItem("unitId")
  if (sessionStorage.getItem("iscp_port")) {
    iscp_port = sessionStorage.getItem("iscp_port");
  } else {
    iscp_port = ""
  }
  let sceneNo = operatorType+''+operatorBasic
  let data = {
    "sceneNo": sceneNo,
    "messageTitle": messageTitle, //笔记标题
    "message": message,
    "orgId": orgId, //单位id
    "userId": userId, //用户id
    "saveType": 3,
    "timestamp": new Date().getTime() + "",
  };
  let AuthenticationSession = sessionStorage.getItem("Authentication");
  data = JSON.stringify(data)
  let sign = sm3(data);
  $.ajax({
    url: localUrlLink + iscp_port +
      "/tjAiAssistant/common/syncToInner",
    type: "post",
    // async: false, //是否同步，false表示同步请求
    dataType: "json",
    data: data,
    headers: {
      "Content-Type": "application/json;charset=UTF-8",
      Authentication: AuthenticationSession,
      sign: sign
    },
    success: (res, txt, xhr) => {
      $(".curtain").css("display", "none");
      if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
        let Authentication = xhr.getResponseHeader("Authentication")
        if (res.code == 200) {
          if (Authentication) {
            sessionStorage.setItem("Authentication", Authentication);
          }
          // syncToast('同步成功', 1500, "success", '101' == sceneNo)
          showConfirmDialog("同步完成，请及时到内网网站aioa.sgcc.com.cn下载使用", " ")
        } else if (res.code == 500) {
          syncToast('同步失败', 1500, "error", '101' == sceneNo)
        }
      } else {
        syncToast('同步失败', 1500, "error", '101' == sceneNo)
      }
    },
    error: (e) => {
      $(".curtain").css("display", "none");
      syncToast('同步失败', 1500, "error", '101' == sceneNo)
    },

  });
}

/**
 * 
 * @param {邮件标题} messageTitle 
 * @param {邮件内容} message 
 * @param {操作分类} operatorType 后台ToEmailEnum枚举类，前面两位10
 * @param {具体操作} operatorBasic 后台ToEmailEnum枚举类，第三位开始
 */
function mySendMail(messageTitle, message, operatorType, operatorBasic) {
  if($(".curtain")) {
    $(".curtain").css("display", "block");
  }
  const userId = sessionStorage.getItem("userId");
  const orgId = sessionStorage.getItem("unitId")
  if (sessionStorage.getItem("iscp_port")) {
    iscp_port = sessionStorage.getItem("iscp_port");
  } else {
    iscp_port = ""
  }
  let sceneNo = operatorType+''+operatorBasic
  let data = {
    "sceneNo": sceneNo,
    "messageTitle": messageTitle, //笔记标题
    "message": message,
    "orgId": orgId, //单位id
    "userId": userId, //用户id
    "timestamp": new Date().getTime() + "",
  };
  let AuthenticationSession = sessionStorage.getItem("Authentication");
  data = JSON.stringify(data)
  let sign = sm3(data);
  $.ajax({
    url: localUrlLink + iscp_port +
      "/tjAiAssistant/common/sendMail",
    type: "post",
    // async: false, //是否同步，false表示同步请求
    dataType: "json",
    data: data,
    headers: {
      "Content-Type": "application/json;charset=UTF-8",
      Authentication: AuthenticationSession,
      sign: sign
    },
    success: (res, txt, xhr) => {
      $(".curtain").css("display", "none");
      if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
        let Authentication = xhr.getResponseHeader("Authentication")
        if (res.code == 200) {
          if (Authentication) {
            sessionStorage.setItem("Authentication", Authentication);
          }
          mui.toast("已发送邮箱", {
            duration: 1000,
            type: 'div'
          })
          addOperator(operatorType, operatorBasic, "发送邮箱", 1, 1, "发送邮箱成功");

        } else if (res.code == 500) {
          mui.toast(res.resultValue, {
            duration: 'long',
            type: 'div'
          })
          addOperator(operatorType, operatorBasic, "发送邮箱", 1, 0, "发送邮箱失败");
        }
      } else {
        mui.toast('完整性校验失败', {
          duration: 'long',
          type: 'div'
        })
        addOperator(operatorType, operatorBasic, "发送邮箱", 1, 0, "发送邮箱失败");
      }

    },
    error: (e) => {
      $(".curtain").css("display", "none");
      mui.toast('请求异常,请稍后再试', {
        duration: 1000,
        type: 'div'
      })
      addOperator(operatorType, operatorBasic, "发送邮箱", 1, 0, "发送邮箱失败");
    },

  });
}

/**
 * 保存分享记录，分享到i国网
 * @param {分享参数} param 
 *  sceneNo：场景号
 *  shareType: 分享类型(0:文本1:文件)
 *  attchId: 分享文件id,shareType为1时必传
 *  content: 分享内容,shareType为0时必传
 * @param {this对象} obj 
 */
function shareIgw(param) {
  $("#curtain").css("display", "block");
  const userId = sessionStorage.getItem("userId");
  param['userId'] = userId
  param['timestamp'] = new Date().getTime() + ""
  let AuthenticationSession = sessionStorage.getItem("Authentication");
  data = JSON.stringify(param)
  let sign = sm3(data);
  $.ajax({
      url: localUrlLink + iscp_port + "/tjAiAssistant/shareIgw/share",
      type: "post",
      async: false, //是否同步，false表示同步请求
      dataType: "json",
      data: data,
      headers: {
          "Content-Type": "application/json;charset=UTF-8",
          Authentication: AuthenticationSession,
          sign: sign
      },
      success: (res, txt, xhr) => {
          if (res.code == 200) {
            let data = res.resultValue
            //分享到i国网
            shareFileToIgw(data.fileName, data.attchId)
          } else {
            $(".curtain").css("display", "none");
              mui.toast('请稍后再试', {
                  duration: 1000,
                  type: 'div'
              })
          }
      },
      error: (e) => {
          $(".curtain").css("display", "none");
          mui.toast('请稍后再试', {
              duration: 1000,
              type: 'div'
          })
      },
  });
}

/**
 * 分享文件到i国网
 * 
 * @param {分享文件名} fileName 
 * @param {分享文件attch表的id} id 
 */
function shareFileToIgw(fileName, id) {
  // let file_arr = fileName.split('.')
  // fileName = file_arr[0] + "_" + new Date().getTime() + "." + file_arr[1]
  let userId = sessionStorage.getItem("userId");
  // let recordArr = JSON.parse(res.result)
  let channelId =
    "temp_upload_" + createNonceStr(16) + new Date().getTime() + "";
  wx.invoke("multiWindows_subscribe",{
      channelId: channelId,
    },(res) => {
      console.log(res.data.result, "监听的数据");
      if (res.data.event == "success") {
        $("#curtain").css("display", "none");
        console.log("下载文件", res.data.result.replace("file://", ""));
        wx.invoke(
          "ext_Intent_SystemShare",
          {
            data: {
              content: decodeURIComponent(res.data.result.replace("file://", "")),
              contentType: "FilePath",
              fileName: unescape(escape(fileName)),
            },
          },
          (res) => {
            wx.invoke(
              "getZipAppDirectory",
              {
                type: "STORAGE_ROOT_DIR", //APP_ROOT_DIR
              },
              res => {
                console.log(res, 999);
                if (compatibleInput()) {
                  wx.invoke(
                    "ext_FileManager_Remove",
                    {
                      data: {
                        fileList: [res.directory + unescape(escape(fileName))],
                      },
                    },
                    res => {
                      console.log("ext_FileManager_Remove", res);
                    }
                  );
                }
              }
            );
          }
        );
      }
    }
  );

  //获取绝对路径
  var path;
  wx.invoke(
    "getZipAppDirectory",
    {
      type: "STORAGE_ROOT_DIR", //STORAGE_ROOT_DIR
    },
    (res) => {
      console.log(res, "路径");
      console.log("分享文件名", fileName)

     
      console.log(unescape(escape(fileName)),"123")
      const userId = sessionStorage.getItem("userId");
      var path = res.directory ? res.directory : "";
      let Authentication = sessionStorage.getItem("Authentication");
      let timestamp = new Date().getTime()+"";
      let sign = sm3(timestamp + '&' + id)
      // 2.开始下载任务
      wx.invoke(
        "ext_Net_Download",
        {
          data: {
            cmd: "download",
            url: localUrlLink + iscp_port + '/tjAiAssistant/common/download?id=' + id + '&userId=' + userId + '&timestamp=' + timestamp + '&Authentication=' + Authentication + '&sign='+sign, //下载url地址
            header: {},
            id: channelId, //与channelId保持一致
            timeout: 10,
            fileName: unescape(escape(fileName)), //保存的文件名
            path: path, //文件保存路径使用getZipAppDirectory获取
          },
        },
        (res) => {
          console.log("downloadfile ", res);
          if (res.event === "start") {
            //任务开始成
            console.log("任务id：", res.id);
          }
          if (res.event === "fail") {
            //任务失败
          }
        }
      );
    }
  );
}

/**
 * 开始录音
 * @param {this对象} that 
 * @param {赋值的文本框id} domId 
 * @param {翻译文字存放在对象中的字段} fieldName 
 * @param {翻译文字存放对象} voiceTxtObj 
 * @param {开始录音回调} startCallback 
 * @param {结束录音回调} endCallBack 
 */
function startLuyin(that, domId, fieldName, voiceTxtObj, startCallback, endCallBack) {
  console.log('----开始录音----')
  mui.toast('正在录音...', {
      duration: '2000',
      type: 'div'
  });
  wx.startRecord();
  //30秒后录音自动停止
  that.time1 = 30;
  console.log(that.time1, "555")
  // 限时30秒说话时间，24秒的时候，提示，30秒后自动暂停
  that.timetimer1 = setInterval(() => {
    that.time1--;
      if (that.time1 == 6) {
          mui.toast('5秒后结束！', {
              duration: 'long',
              type: 'div'
          });
      }
      if (that.time1 == 0) {
          endVoice(that, domId, fieldName, voiceTxtObj, endCallBack)
      }
  }, 1000);
  // 打开语音翻译功能
  wx.onVoiceRecordEnd({
      complete: (res) => {
          console.log(res, "localId")
          let localId = res.localId;
          if (localId) {
              if (that.voicelist.findIndex((item) => item == localId) == -1) {
                that.voicelist.push(localId);
              }
          }
          $(that).click();
      }
  });
  if(startCallback) {
    startCallback();
  }
}

/**
 * 结束录音
 * @param {this对象} that 
 * @param {赋值的文本框id} domId 
 * @param {翻译文字存放在对象中的字段} fieldName 
 * @param {翻译文字存放对象,不传则默认this} voiceTxtObj
 * @param {结束录音回调} endCallBack 
 */
function endLuyin(that, domId, fieldName, voiceTxtObj, endCallBack) {
  console.log('----结束录音----')
  clearInterval(that.timetimer1)
  that.time1 = 30
  that.time = clearInterval(that.time)
  window.clearInterval($(that).data("interval"));
  // 暂停
  wx.stopRecord({
      success: (res) => {
          let localId = res.localId;
          console.log(res, "res")
          if (localId) {
              if (that.voicelist.findIndex((item) => item == localId) == -1) {
                that.voicelist.push(localId);
                text(that, domId, fieldName, voiceTxtObj, endCallBack)
              }
          }
      }
  });
}

/**
 * 翻译录音文本
 * @param {this对象} that 
 * @param {赋值的文本框id} domId 
 * @param {翻译文字存放在对象中的字段} fieldName 
 * @param {翻译文字存放对象} voiceTxtObj 
 * @param {结束录音回调} endCallBack 
 */
function text(that, domId, fieldName, voiceTxtObj, endCallBack) {
  if ($(that).data("localId")) {
    that.voicelist.currentIndex = $(that).data("localId");
  }
  wx.translateVoice({
      localId: that.voicelist[that.voicelist.length - 1],
      isShowProgressTips: 1,
      success: (res) => {
          console.log(res, res.translateResult, "内容")
          voiceTxtObj = voiceTxtObj || that
          var $input1 = document.getElementById(domId); //获取光标
          if ($input1.selectionStart == 0) { //如果是没有点input ,说话直接拼接
            voiceTxtObj[fieldName] += res.translateResult
          } else if (voiceTxtObj[fieldName].length == $input1.selectionStart) { //是否在最后
            voiceTxtObj[fieldName] += res.translateResult
          } else { //点击时候是否为0位
            voiceTxtObj[fieldName] = voiceTxtObj[fieldName].slice(",", $input1.selectionStart) + res
                  .translateResult + voiceTxtObj[fieldName].slice($input1.selectionStart)
          }
          if(endCallBack) {
            endCallBack();
          }
      }
  });
}

/**
 * 清除定时器
 * @param {定时器} timer 
 */
function clearIntervalTimer(timer) {
  if(timer) {
    return clearInterval(timer)
  }
  return null;
}

/**
 * 添加待处理的敏感词数据
 * @param {场景号} sceneNo 
 * @param {附件id} attachId 
 */
function addPendingData(sceneNo, attachId) {
  let timestamp = new Date().getTime() + ""
  userId = sessionStorage.getItem("userId");
  let sign = sm3(timestamp + "&" + userId) 
  let AuthenticationSession = sessionStorage.getItem("Authentication");
  let param = {
    sceneNo: sceneNo,
    attachId: attachId,
    userId: userId
  }
  data = JSON.stringify(param)


  // 构建请求配置
  const requestOptions = {
      method: "POST",
      headers: {
          "Content-Type": "application/json;charset=UTF-8",
          Authentication: AuthenticationSession,
          sign: sign
      },
      body: data
  };

  // 发起请求
  const response = fetch(localUrlLink + iscp_port + "/tjAiAssistant/sensitivePending/addPendingData", requestOptions);

    console.log("敏感词校核结果", response)
}

/**
 * 获取用户资源权限
 */
function havePermissions(resId, domId) {
  let resources = JSON.parse(sessionStorage.getItem("newMenus"))
  console.log("权限", resources)
  if(null != resources && 0 < resources.length) {
     return resources.some(resource => resId == resource.id && resource.buttonIds && 
      resource.buttonIds.indexOf(domId) != -1)
  }
  return false
}

/**
 * 获取当前大模型类型： BAIDU, ALI
 */
function getLargeModelType() {
  let largeModel = localStorage.getItem("largeModel")
  if(!largeModel) {
    largeModel = 'ALI'
  }
  return largeModel
}